package nautilus.moneykeeper.adapter;

import java.text.SimpleDateFormat;
import java.util.ArrayList;

import nautilus.moneykeeper.R;
import nautilus.moneykeeper.dto.Transaction;
import nautilus.moneykeeper.system.Constant;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class ListTransAdapter extends BaseAdapter{

	private ArrayList<Transaction> _transactions = new ArrayList<Transaction>();
	private SimpleDateFormat _format = new SimpleDateFormat(Constant.DATE_FORMAT_MMDDYYYY_HHMM);
	LayoutInflater _inflater;
	private static final int[] bgColors = new int[] { 0x30FF0000, 0x300000FF };
	
	public ListTransAdapter(Activity activity, ArrayList<Transaction> transactions) {		
		_transactions.addAll(transactions);
		_inflater =  (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}
	
	@Override
	public int getCount() {
		return _transactions.size();
	}

	@Override
	public Transaction getItem(int arg0) {
		return  _transactions.get(arg0);
	}

	@Override
	public long getItemId(int arg0) {
		return _transactions.get(arg0).getId();
	}

	
	public void refreshData(ArrayList<Transaction> transactions){
		_transactions.clear();
		_transactions.addAll(transactions);
		//transactions = null;
		notifyDataSetChanged();
	}
	
	public void addMoreData(ArrayList<Transaction> transactions){
		_transactions.addAll(transactions);
		transactions = null;
		notifyDataSetChanged();
	}
	
	@Override
	public View getView(int pos, View convertView, ViewGroup vg){
		View transView = convertView;
		TransView tView;
		
		if(transView == null){
			//get an instance of row layout
			transView = _inflater.inflate(R.layout.list_trans_item, null);
			
			tView = new TransView();
			tView.tvCategory = (TextView)transView.findViewById(R.id.tvCagegory);
			tView.tvDateTime = (TextView)transView.findViewById(R.id.tvDateTime);
			tView.tvAmount = (TextView)transView.findViewById(R.id.tvAmount);
			
			transView.setTag(tView);
			
		}else{
			tView = (TransView)transView.getTag();
		}
		
		Transaction transaction = _transactions.get(pos);
		tView.tvCategory.setText(transaction.getCategory().getName());
		tView.tvDateTime.setText(_format.format(transaction.getDatetime()));
		tView.tvAmount.setText(transaction.getAmount()+"(" + transaction.getAccount().getCurrencyUnit().getName()+")");
		
		int icolor = pos % bgColors.length;
		transView.setBackgroundColor(bgColors[icolor]);
		
		return transView;
	}
	
	protected final class TransView{
		protected TextView tvCategory, tvDateTime, tvAmount;
	}
}
